/*
 * Copyright (c) 2022. CloudStar.Co.Ltd. All rights reserved.
 */

package cn.com.config.encryptor;


import cn.com.config.detector.CloudStarEncryptablePropertyDetector;
import cn.com.utils.crypto.CrytoUtil;
import org.jasypt.encryption.StringEncryptor;

/**
 * 默认加密机
 */
public class DefaultEncryptor implements StringEncryptor {

    /**
     * 属性检测器
     */
    private CloudStarEncryptablePropertyDetector propertyDetector;

    public DefaultEncryptor(CloudStarEncryptablePropertyDetector propertyDetector) {
        this.propertyDetector = propertyDetector;
    }

    /**
     * 加密，不需要加密直接使用
     *
     * @param encryptMessage 配置值
     * @return {@link String}
     */
    @Override
    public String encrypt(String encryptMessage) {
        return encryptMessage;
    }

    /**
     * 先还原原密文，再还原原密码
     *
     * @param decryptMessage 加密后的值
     * @return {@link String}
     */
    @Override
    public String decrypt(String decryptMessage) {
        String prefix = propertyDetector.getPrefix();
        String suffix = propertyDetector.getSuffix();
        int prefixIndex = decryptMessage.indexOf(prefix);
        int suffixIndex = decryptMessage.indexOf(suffix);
        //还原密文
        decryptMessage = decryptMessage.substring(prefixIndex + prefix.length(), suffixIndex);
        //还原密码。注意如果需要密钥的这里添加
        return CrytoUtil.decrypt(decryptMessage, false).trim();
    }
}
